Membership operators are used to test whether a sequence is present in an object. There are two types of membership operators in Python:
in: This operator returns True if it finds a specified value in a given sequence and False otherwise. It’s used to check if a character, substring, or element exists in a sequence.
Membership operator (in) example in python
x = 'Hello, World!'
print('Hello' in x)
Output
True
In this example, 'Hello' in x returns True because the string 'Hello' is found in the string x.
not in: This operator returns True if it does not find a specified value in a given sequence and False otherwise.
Membership operator (not in) example in python
x = 'Hello, World!'
print('Goodbye' not in x)
Output
True
In this example, 'Goodbye' not in x returns True because the string 'Goodbye' is not found in the string x.
These operators can be used with any sequence, such as strings, lists, or tuples.